package com.zzx.controller;

import com.zzx.Util.JSONUtil;
import com.zzx.bean.Message;
import com.zzx.service.imp.AdminService;
import com.zzx.servlet.ResponseText;
import com.zzx.servlet.ResponseView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

/**
 * @Author: Spider Man
 * @Description:
 * @Date Created in 2020-09-11 14:36
 * @Modified By:
 */
public class AdminController {

    @ResponseText("/admin/login.do")
    public String login(HttpServletRequest request, HttpServletResponse response){
        // 1.接参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 2.调用servlet传参数并获取结果
        AdminService adminService = new AdminService();
        boolean result = adminService.login(username,password);
        Message message = null;
        if (result){
            message = new Message(0,"登录成功");
            //更新登录时间和ip
            Date date = new Date();
            String ip = request.getRemoteAddr();
            adminService.updateLoginTime(username,date,ip);
            request.getSession().setAttribute("adminUsername",username);
        }else {
            message = new Message(-1,"用户名或密码不正确");
        }
        return JSONUtil.toJSON(message);
    }

    @ResponseText("/admin/loginOut.do")
    public String loginOut(HttpServletRequest request, HttpServletResponse response){
        request.getSession().setAttribute("adminUsername",null);
        Message message = new Message();
        if (request.getSession().getAttribute("adminUsername") == null){
            message.setStatus(0);
            message.setResult("退出成功,1s后返回登录界面");
        }else {
            message.setStatus(-1);
            message.setResult("退出失败");
        }
        return JSONUtil.toJSON(message);
    }
}
